'use strict';

const Service = require('egg').Service;
const { Op } = require('sequelize');

class RolesService extends Service {

  /**
   * @description: 角色列表接口
   * @param {*} payload
   * @return {*}
   */
  async index(payload) {
    const { ctx } = this;
    const { pageSize, current, prop_order, order } = payload;
    const where = payload.where;
    const Order = [];
    prop_order && order ? Order.push([ prop_order, order ]) : null;
    // 如果请求者不是用户id为1的超级管理员，则不返回id为1的超级管理员角色
    if (ctx.helper.getUserIdByHeader(ctx) !== 1) {
      if (where[Op.and]) {
        where[Op.and].push({ id: { [Op.ne]: 1 } });
      } else {
        where[Op.and] = [{ id: { [Op.ne]: 1 } }];
      }
    }
    const rsp = await ctx.model.TRoles.findAndCountAll({ limit: pageSize || 10, offset: current ? current - 1 : 0, where, order: Order });
    if (rsp) {
      return ctx.helper.body.SUCCESS({ ctx, msg: '角色列表获取成功', data: { list: rsp.rows, total: rsp.count, current, pageSize: pageSize || 10 } });
    }
    return ctx.helper.body.ERROR({ ctx, msg: '角色列表获取失败' });
  }


  /**
   * @description: 角色新增
   * @param {*} payload
   * @return {*}
   */
  async add(payload) {
    const { ctx } = this;
    const { role_name, remark, resourceIds } = payload;
    const role = await ctx.model.TRoles.findOne({
      where: { role_name },
    });
    if (role) {
      return ctx.helper.body.ERROR({ ctx, msg: '角色名称已存在' });
    }
    const rsp = await ctx.model.TRoles.create({ role_name, remark, is_default: 0 });
    ctx.logger.info('======角色新增成功返回=====', rsp);
    if (rsp) {
      const arr = [];
      resourceIds.split(',').forEach(item => {
        arr.push({ role_id: rsp.dataValues.id, resource_id: item });
      });
      await ctx.model.TRolesResources.bulkCreate(arr);
      return ctx.helper.body.SUCCESS({ ctx, msg: '角色新增成功', data: null });
    }
  }

  /**
   * @description: 获取角色详情
   * @param {*} payload
   * @return {*}
   */
  async getInfo(payload) {
    const { ctx, app } = this;
    const { id } = payload;
    const role = await ctx.model.TRoles.findOne({ attributes: [ 'id', 'role_name' ], where: { id } });
    const resourceList = await ctx.model.TResources.findAll({ attributes: [ 'id', [ 'name_cn', 'title' ], 'kind', 'parent_id', [ 'id', 'key' ]], where: { status: 1 }, raw: true });
    // const checkList = await ctx.model.TRolesResources.findAll({ attributes: [ 'resource_id' ], where: { role_id: id }, raw: true });
    const checkIdList = await app.mysql.query(`select a.id
    from t_resources a
    left join t_roles_resources b on a.id = b.resource_id
    where b.role_id = ${id}
    and a.id not in (select a.parent_id from	t_resources a inner join t_roles_resources b on a.id = b.resource_id and b.role_id = ${id})
    ORDER by a.parent_id, a.sort`);
    ctx.logger.info('=======checkIdList=======', checkIdList);
    return ctx.helper.body.SUCCESS({ ctx, msg: '获取成功', data: { role, checkList: ctx.helper.getArrayProps(checkIdList, 'id'), resourceList: ctx.helper.arrayToTree(resourceList), resourceIdList: ctx.helper.getArrayProps(resourceList, 'id') } });
  }

  /**
   * @description: 角色修改
   * @param {*} payload
   * @return {*}
   */
  async update(payload) {
    const { ctx } = this;
    const { role_name, remark, id, resourceIds } = payload;
    // if (id === 1) {
    //   return ctx.helper.body.ERROR({ ctx, msg: '超级管理员角色不允许修改' });
    // }
    const transaction = await ctx.model.transaction();
    const role = await ctx.model.TRoles.findOne({
      where: { role_name },
      raw: true,
    });
    if (role && role.role_name !== role_name) {
      return ctx.helper.body.ERROR({ ctx, msg: '角色名称已存在' });
    }
    await ctx.model.TRolesResources.destroy({ where: { role_id: id } }, { transaction });
    const arr = [];
    resourceIds.split(',').forEach(item => {
      arr.push({ role_id: id, resource_id: item });
    });
    await ctx.model.TRolesResources.bulkCreate(arr, { transaction });
    await ctx.model.TRoles.update({ role_name, remark }, { where: { id } }, { transaction });
    await transaction.commit();
    return ctx.helper.body.SUCCESS({ ctx, msg: '角色修改成功', data: null });
  }

  /**
   * @description: 删除角色
   * @param {*} payload
   * @return {*}
   */
  async destroy(payload) {
    const { ctx } = this;
    const { ids } = payload;
    const roleUser = await ctx.model.TRolesUsers.findAll({
      where: { role_id: { [Op.or]: ids } },
      include: [{ model: ctx.model.TRoles, attributes: [ 'role_name' ] }],
      raw: true, // 表明返回的数据是json而不是model
    });
    if (roleUser && roleUser.length > 0) {
      ctx.logger.info('=====roleUser=====', roleUser);
      if (roleUser[0]['t_role.role_name'] === '超级管理员') {
        return ctx.helper.body.ERROR({ ctx, msg: `【${roleUser[0]['t_role.role_name']}】角色不能删除` });
      }
      return ctx.helper.body.ERROR({ ctx, msg: `【${roleUser[0]['t_role.role_name']}】角色已绑定用户无法删除` });
    }
    const allRoles = await ctx.model.TRoles.findAll({
      where: { id: { [Op.or]: ids } },
    });
    if (!allRoles.every(e => e.is_default !== 1)) {
      return ctx.helper.body.ERROR({ ctx, msg: '默认角色不能删除' });
    }
    await ctx.model.TRolesResources.destroy({ where: { role_id: { [Op.or]: ids } } });
    await ctx.model.TRoles.destroy({ where: { id: { [Op.or]: ids } } });
    return ctx.helper.body.SUCCESS({ ctx, msg: '角色删除成功', data: null });
  }

  /**
   * @description: 修改角色为默认角色
   * @param {*} payload
   * @return {*}
   */
  async updateIsDefault(payload) {
    const { ctx } = this;
    const transaction = await ctx.model.transaction();
    await ctx.model.TRoles.update({ is_default: 0 }, { where: { is_default: 1 }, transaction });
    const res = await ctx.model.TRoles.update({ is_default: 1 }, { where: { id: payload.id }, transaction });
    if (res && res[0] === 1) {
      await transaction.commit();
      return ctx.helper.body.SUCCESS({ ctx, msg: '操作成功', data: null });
    }
    await transaction.rollback();
    return ctx.helper.body.ERROR({ ctx, msg: '操作失败' });
  }


}
module.exports = RolesService;
